import api from './config';
import qs from 'qs';
import { witLog } from '@/witUI/log/logColor';
import { getToken } from '@/store/storage'
import { nextTick } from "vue";
import { useErrorLog } from '@/store/pinia/modules/errorLog'
import Crypto from '@/store/encryption'

const crypto = new Crypto();
// 多个loading合并为一个
let needLoadingRequestCount = 0
export function showLoading() {
    if (needLoadingRequestCount === 0) {
        uni.showLoading({
            title: '加载中...',
        })
    }
    needLoadingRequestCount++
}
export function hideLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        uni.hideLoading()
    }
}

/**
 * request function
 * @param url      请求url
 * @param method get,post,put,delete
 * @param params 参数
 * @param level  0:无加密，1：参数加密，2: 签名+时间戳, 3: 1+2； 默认0
 */
const request = (url: string, method: string, params?: any, level=0) => {
    showLoading();
    const errorStore = useErrorLog();
    const { setErrorLogInfo } = errorStore;
    // 获取token
    const token = getToken() || ''
    // if (token && !config.headers?.Authorization) {
    //     config.headers = { ...config.headers, Authorization: token }
    // }
    const header = {
        'content-type': api.contentType,
        'Authorization': 'Bearer ' + token,
        level,
    }
    if (method === 'POST' || method === 'PUT') {
        // post请求时，处理数据
        params = qs.stringify({
            ...params
            // 后台数据接收这块需要以表单形式提交数据，而axios中post默认的提交是json数据,所以这里选用qs模块来处理数据，也有其他处理方式，但个人觉得这个方式最简单好用
        })
    }
    // 加密
    if (level === 1) {
        params = {data: crypto.enAes(params)};
    } else if (level === 2) {
        //  签名
        const times = new Date().getTime();
        const signStr = crypto.sign(token, times, params);
        console.log('签名：',signStr);
        header['times'] = times;
        header['signStr'] = signStr;
    } else if (level === 3) {
        // 参数加密
        params = {data: crypto.enAes(params)};
        //  签名
        const times = new Date().getTime();
        const signStr = crypto.sign(token, times, params);
        console.log('签名：',signStr);
        header['times'] = times;
        header['signStr'] = signStr;
    }

    method = (method === undefined || method === '') ? 'GET' : method.toUpperCase();

    return new Promise((resolve, reject) => {
        // console.log(api.HostUrl + url)
        uni.request({
            url: api.HostUrl + url,
            data: params,
            // @ts-ignore
            method,
            header: header,
            success: (response) => {
                console.log(response)
                hideLoading();
                if (response.statusCode >= 200) {
                    // @ts-ignore
                    const {code, url: url1, msg} = response.data
                    if (code >= 400) {
                        uni.showToast({
                            title: msg,
                            icon: 'none'
                        })
                        witLog.witLog('Wit-UI', '请求报错', 'warning')
                        witLog.witError(msg, url1, code,'error')
                        // @ts-ignore
                        if (response.data.url !== '/log/addLog/') {
                            nextTick(() => {
                                const err = {
                                    err: {
                                        message: msg
                                    },
                                    errRoter: url1,
                                    info: '请求接口报错',
                                    code: code,
                                    params: params,
                                    requestMethods: method,
                                    routerService: url

                                }
                                setErrorLogInfo(err).then();
                            }).then()
                        }
                    }
                    // else {
                    //     uni.showToast({
                    //         title: response.data.msg
                    //     })
                    // }
                    resolve(response.data)
                } else {
                    reject(response.data)
                }
            },
            fail: (err) => {
                console.log(err)
                hideLoading();
                witLog.witLog('Wit-UI', '请求报错', 'error')
                witLog.error(err.errMsg)
                uni.showToast({
                    icon: 'none',
                    title: err.errMsg,
                    duration: 2000
                });
                reject(err)
            }
        })
    })
}
export default request